//
//  UserNameEditViewController.Action.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/2/11.
//

import Center
import Foundation
import RxCocoa
import RxSwift
import UICore
import UIKit

extension UserNameEditViewController {
    func bind() {
        usernameTextField.rx.text.orEmpty.asObservable()
            .subscribe(onNext: { [self] text in
//                var value = text
//                if value.count > self.maxUsernameLength {
//                    value = value.slicing(from: 0, length: self.maxUsernameLength) ?? ""
//                    usernameTextField.text = value
//                }
                self.countLabel.text = "\(self.maxUsernameLength - text.count)"
            })
            .disposed(by: disposeBag)
    }

    @objc
    func confirm() {
        guard let text = usernameTextField.text, !text.isEmpty else {
            view.makeToast(ProfileModular.localizedString(key: "Profile.Userinfo.Username.Empty"), position: .center)
            return
        }

        if text == UserCenter.userInfo?.username {
            back()
            return
        }

        view.makeToastActivity(.center)
        UserCenter.updateBasicProfile(username: text) { [weak self] result in
            self?.view.hideToastActivity()
            switch result {
            case .success:
                self?.back()
            case .failure(let error):
                self?.view.makeToast(error.localizedDescription, position: .center)
            }
        }
    }
}

extension UserNameEditViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_: UITextField) -> Bool {
        confirm()

        return true
    }
}
